Categories
Day.js

Manipulating Dates with Day.js — Set ISO Day of the Week and Day of the Year

Spread the love

Day.js is a JavaScript library that lets us manipulate dates in our apps.

In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.

Set the ISO Day of the Week of a Date

To set the ISO day of the week in a Day.js date we can use the isoWeekday method available with the isoWeek plugin:

const dayjs = require("dayjs");
const isoWeek = require("dayjs/plugin/isoWeek");
dayjs.extend(isoWeek);

const result = dayjs().isoWeekday(1);
console.log(result);

We import the isoWeek plugin with:

const isoWeek = require("dayjs/plugin/isoWeek");

And we set the ISO day of the week to Monday by calling isoWeekday with 1.

Set the Day of the Year of a Date

To set the day of the year in a Day.js date we can use the dayOfYear method available with the dayOfYear plugin:

const dayjs = require("dayjs");
const dayOfYear = require("dayjs/plugin/dayOfYear");
dayjs.extend(dayOfYear);

const result = dayjs().dayOfYear(1);
console.log(result);

We import the isoWeek plugin with:

const dayOfYear = require("dayjs/plugin/dayOfYear");

And we set the day of the year to the first day by calling isoWeekday with 1.

If the day of the year exceeds the number of days in the year, then the year will be increased accordingly.

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *